<?php
/***************************************************************
 *  Copyright notice
 *
 *  (c) 2011 Martin Klein <mklein@webpages.de>, Webpages.de
 *
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/


/**
 * Controller for the Videos object
 */
class Tx_Pfcontest_Controller_VideosController extends Tx_Extbase_MVC_Controller_ActionController {

    protected $setMoveToPath          = "/home/powderful_step2/video/";
    protected $setMoveToPathConverted = "/home/powderful_step2/www/fileadmin/converted/";
    protected $videosOnPage           = 15;
    protected $youTubeUser            = "got2bpowderful";
    /**
     * videosRepository
     *
     * @var Tx_Pfcontest_Domain_Repository_VideosRepository
     */
    protected $videosRepository;

    /**
     * Dependency injection of the Videos Repository
     *
     * @param Tx_Pfcontest_Domain_Repository_VideosRepository $videosRepository
     * @return void
     */
    public function injectBlogRepository(Tx_Pfcontest_Domain_Repository_VideosRepository $VideosRepository) {
        $this->videosRepository = $videosRepository;
    }

    /**
     * Initializes the current action
     *
     * @return void
     */
    protected function initializeAction() {
        $this->videosRepository = t3lib_div::makeInstance('Tx_Pfcontest_Domain_Repository_VideosRepository');
    }

    /**
     * Creates a new Videos and forwards to the list action.
     *
     * @param Tx_Pfcontest_Domain_Model_Videos $newVideos a fresh Videos object which has not yet been added to the repository
     * @return void
     * @dontvalidate
     */
    public function uploadAction() {
        //public function uploadAction(Tx_Pfcontest_Domain_Model_Videos $newVideos = null) {

        //GET POST holen
        $request         = $this->request->getArguments();
        $fileWasUploaded = false;
        $error           = false;

        //Überprüfung der Eingabefelder
        if($request['newVideos']){
            if($request['newVideos']['username'] == 'NICKNAME'){
                $error = true;
                $this->view->assign('e_username', 'error');
            }else{
                $this->view->assign('v_username', $request['newVideos']['username']);
            }

            //Überprüfung der Eingabefelder
            //if($request['newVideos']['email'] == 'E-MAIL'){
            if(!preg_match("/^(?=.{5,254})(?:(?:\"[^\"]{1,62}\")|(?:(?!\.)(?!.*\.[.@])[a-z0-9!#$%&'*+\/=?^_`{|}~^.-]{1,64}))@(?:(?:\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\])|(?:(?!-)(?!.*-\$)(?!.*-\.)(?!.*\.-)(?!.*[^n]--)(?!.*[^x]n--)(?!n--)(?!.*[^.]xn--)(?:[a-z0-9-]{1,63}\.){1,127}(?:[a-z0-9-]{1,63})))$/i", $request['newVideos']['email'])){
                $error = true;
                $this->view->assign('e_email', 'error');
            }else{
                $this->view->assign('v_email', $request['newVideos']['email']);
            }

            //Überprüfung der Eingabefelder
            if($request['newVideos']['videoname'] == 'VIDEONAME'){
                $error = true;
                $this->view->assign('e_videoname', 'error');
            }else{
                $this->view->assign('v_videoname', $request['newVideos']['videoname']);
            }

            //Überprüfung der Eingabefelder
            if($request['legal'] != 1){
                $error = true;
                $this->view->assign('e_legal', 'error');
            }
            //Überprüfung der Eingabefelder
            if($request['nofacebook'] != 1){
                $error = true;
                $this->view->assign('e_nofacebook', 'error');
            }
            //Überprüfung der Eingabefelder
            if(!$_FILES['tx_pfcontest_vcontest']["name"]["newVideos"]["myfile"]){
                $error = true;
                $this->view->assign('e_myfile', 'error');
            }
        }

        if($error == false){

            $exFileExtentsion = explode('.', $_FILES['tx_pfcontest_vcontest']["name"]["newVideos"]["myfile"]);
            $uploadFilename   = "contest".rand(1,100000).".".$exFileExtentsion[sizeof($exFileExtentsion)-1];
            //FileUpload Config
            if($_FILES['tx_pfcontest_vcontest']){

                $fileUpload = new Tx_Pfcontest_Domain_Model_Fileupload();
                $fileUpload->setUploadFile($_FILES['tx_pfcontest_vcontest']);
                $fileUpload->setFileTypes(array('mov', 'mpeg', 'mp4', 'flv', '3gp', 'mpg', 'avi', 'wmv'));
                $fileUpload->setMaxFileSize(102400000);
                $fileUpload->setMoveToPath($this->setMoveToPath);
                $fileUpload->setNewName($uploadFilename);
                $fileUpload->setUploadMode('video');

                $fileWasUploaded = $fileUpload->uploadFile();
                $this->view->assign('e_myfile', 'error');

            }

            $this->flashMessages->add('fileWasUploaded->'.$fileWasUploaded);
            //alles okay mit dem Upload dann ab Datensatz anlegen
            if($fileWasUploaded == true){

                //SysLanguageId setzen
                $request['newVideos']['sys_language_uid'] = $GLOBALS['TSFE']->sys_language_uid;

                //$test = $this->videosRepository->add($newVideos);
                $uid = $this->videosRepository->insertVideo($request['newVideos']) ;

                $this->flashMessages->add('Inserting Video');

                //Meta Infos holen aus UploadVideo
                //exec('ffmpeg -i '.$this->setMoveToPath.$uploadFilename, $ausgabe);
                exec('mediainfo  '.$this->setMoveToPath.$uploadFilename, $ausgabe);

                $getInfos = false;

                foreach($ausgabe AS $row){

                    if(trim($row) == "Video"){
                        $getInfos = true;
                    }
                    if(trim($row) == "Audio"){
                        $getInfos = false;
                    }

                    //Breite
                    if($getInfos == true){
                        if(preg_match('(Width)', $row)){
                            $width = trim(preg_replace('(Width|:|pixels)', '', $row));
                        }
                        //Höhe
                        if(preg_match('(Height)', $row)){
                            $height = trim(preg_replace('(Height|:|pixels)', '', $row));
                        }
                        //Bit rate
                        if(preg_match('(Bit rate)', $row)){
                            if(preg_match('(\.)', $row)){
                                $ex = explode('.', $row);
                                $b = trim(preg_replace('(Bit rate|:| |Kbps)', '', $ex[0]))."000";
                            }else{
                                $b = trim(preg_replace('(Bit rate|:| |Kbps)', '', $row))."000";
                            }
                        }
                        //FrameRate
                        if(preg_match('(Frame rate)', $row)){
                            $r = trim(preg_replace('(Frame rate|:| |fps)', '', $row));
                        }
                    }
                }

                //Convert Uploaded Video to FLV
                exec('ffmpeg -i '.$this->setMoveToPath.$uploadFilename.' -s '.$width.'x'.$height.' -deinterlace -ar 44100 -r '.$r.' -b '.$b.' -acodec libmp3lame -ac 2 '.$this->setMoveToPathConverted.'contest'.$uid.'.flv');
                //echo 'ffmpeg -i '.$this->setMoveToPath.$uploadFilename.' -s '.$width.'x'.$height.' -deinterlace -ar 44100 -r '.$r.' -b '.$b.' -acodec libmp3lame -ac 2 '.$this->setMoveToPathConverted.'contest'.$uid.'.flv';
                //exit;
                exec('ffmpeg -i '.$this->setMoveToPathConverted.'abbinder_orig.mov -s '.$width.'x'.$height.' -deinterlace -ar 44100 -r '.$r.' -b '.$b.' -acodec libmp3lame -ac 2 '.$this->setMoveToPathConverted.'abbinder.flv');
                sleep(10);
                //Merge Uploaded file with "abbinder"
                exec('mencoder -forceidx -of lavf -oac pcm -ovc copy '.$this->setMoveToPathConverted.'contest'.$uid.'.flv ' .$this->setMoveToPathConverted.'abbinder.flv -o '.$this->setMoveToPathConverted.'contest'.$uid.'_full.flv');
                //echo 'mencoder -forceidx -of lavf -oac pcm -ovc copy '.$this->setMoveToPathConverted.'contest'.$uid.'.flv ' .$this->setMoveToPathConverted.'abbinder.flv -o '.$this->setMoveToPathConverted.'contest'.$uid.'_full.flv';
                //Orgnialfile wegmoven ins Archiv
                exec('mv '.$this->setMoveToPath.$uploadFilename.' '.$this->setMoveToPath."contest".$uid.".".$exFileExtentsion[sizeof($exFileExtentsion)-1]);
                exec('rm '.$this->setMoveToPathConverted.'abbinder.flv');


                //Update Video Entry
                $updater = $this->videosRepository->findByUid($uid);
                $updater->setVideokey("contest".$uid."_full.flv");
                $this->videosRepository->update($updater);

                //$this->redirect('thx');
                $this->redirect ('', '', '', array(), $pageUid=28, '', $statusCode=303);

            }

            //FINAL!!

            //convertieren parameter  -b und -r und das beim abbinder und beim orginal
            // ffmpeg -i Auf_Got2B_Powderfull_Abbinder_Chauf040411bc1730av02.mov -s 320x240 -b 2181000 -deinterlace -ar 44100 -r 15 -acodec libmp3lame -ac 2 abbinder2.flv

            //zusammenführen
            //mencoder -forceidx -of lavf -oac copy -ovc copy con1.flv abbinder2.flv -o full_movie2.flv
        }

    }



    /**
     * Einbinden vom Coverflow auf der Startseite
     *
     */
    public function coverflowAction(){

        //Playlisten Unterscheidung anhand der sys_language_uid
        $arrayPlaylistKeys = array(   '0' => 'powderful_de',
            '1' => 'powderful_ch',
            '2' => 'powderful_no'
        );

        $gallery = new Tx_Pfcontest_Domain_Model_Youtube();
        $feeds = $gallery->getPlaylistEntries($this->youTubeUser, $arrayPlaylistKeys[$GLOBALS['TSFE']->sys_language_uid]);

        usort($feeds, 'vergleich');

        $arrayPageVideos = array();
        for($i = 0; $i < 12; $i++ ){
            if(trim($feeds[$i]['videoName']) == "" ){
                continue;
            }
            array_push($arrayPageVideos, $feeds[$i]);
        }

        $this->view->assign('feeds', $arrayPageVideos);
    }

    /**
     * Displays all Channel Videos
     *
     * @return void
     */
    public function galleryAction() {

        //Playlisten Unterscheidung anhand der sys_language_uid
        $arrayPlaylistKeys = array(   '0' => 'powderful_de',
            '1' => 'powderful_ch',
            '2' => 'powderful_no'
        );

        $gallery = new Tx_Pfcontest_Domain_Model_Youtube();

        if($_POST['abschicken'] == 'abschicken'){
            $feeds = $gallery->searchVideoByTitle($this->youTubeUser, $arrayPlaylistKeys[$GLOBALS['TSFE']->sys_language_uid], $_POST['suche']);
        }else{
            $feeds = $gallery->getPlaylistEntries($this->youTubeUser, $arrayPlaylistKeys[$GLOBALS['TSFE']->sys_language_uid]);
        }

        //GET POST Parameter holen
        $request = $this->request->getArguments();

        //Page Auslesen
        if( $request['page'] ){
            $page = $request['page'];
        }

        //Seiten und Array Positionen bestimmen
        if($page < 1){
            $page = 1;
            $from = 0;
            $till = $this->videosOnPage;
        }else{
            $from = ($page - 1) * $this->videosOnPage;
            $till = ($page ) * $this->videosOnPage;;
        }

        //Gesamtseiten Anzahl berechnen
        $totalPages = ceil(sizeof($feeds)/$this->videosOnPage);

        $arrayPageVideos = array();
        //echo $from."-".$till."<br>";
        for($i = $from; $i < $till; $i++ ){
            if(trim($feeds[$i]['videoName']) == "" ){
                continue;
            }
            array_push($arrayPageVideos, $feeds[$i]);
        }

        if(($page -1) == 0 ){
            $pageF = 1;
        }else{
            $pageF = $page -1;
        }

        //Übergabe an den View
        $this->view->assign('feeds', $arrayPageVideos);
        $this->view->assign('page', $page);
        $this->view->assign('pageF', $pageF);
        $this->view->assign('pageT', $page +1);
        $this->view->assign('totalPages', $totalPages);
    }

    /**
     * Displays VideoDetail
     *
     * @return void
     */
    public function videoAction() {

        //Playlisten Unterscheidung anhand der sys_language_uid
        $arrayPlaylistKeys = array(   '0' => 'powderful_de',
            '1' => 'powderful_ch',
            '2' => 'powderful_no'
        );

        $gallery = new Tx_Pfcontest_Domain_Model_Youtube();
        $feeds = $gallery->getVideoById($_GET['feed']);
        $this->view->assign('feed', $feeds);

        //Related Video Sildebar
        $allFeeds = $gallery->getPlaylistEntries($this->youTubeUser, $arrayPlaylistKeys[$GLOBALS['TSFE']->sys_language_uid]);

        shuffle($allFeeds);

        //Nur 12 Videos max. Anzeigen
        $arrayPageVideos = array();
        for($i = 0; $i < 12; $i++ ){
            if(trim($allFeeds[$i]['videoName']) == "" ){
                continue;
            }
            array_push($arrayPageVideos, $allFeeds[$i]);
        }

        $this->view->assign('allFeed', $arrayPageVideos);

        //facebook link
        //$link = $this->uriBuilder->uriFor('video', null);
        $link = $this->uriBuilder->uriFor('video', null);

        //echo $link;
        $this->view->assign('facebookLink', $link."?feed=". $_GET['feed']);

    }

    /**
     * Displays all Videos
     *
     * @return void
     */
    public function thxAction() {

        /**
         * do nothing
         */
    }

    /**
     * Displays Danke Seite
     *
     * @return void
     */
    public function listAction() {
        $videos = $this->videosRepository->findAll();
        $this->view->assign('img_videos', $videos);
    }

    /**
     * Displays a single Videos
     *
     * @param Tx_Pfcontest_Domain_Model_Videos $videos the Videos to display
     * @return string The rendered view
     */
    public function showAction(Tx_Pfcontest_Domain_Model_Videos $videos) {
        $this->view->assign('img_videos', $videos);
    }

    /**
     * Displays a form for creating a new  Videos
     *
     * @param Tx_Pfcontest_Domain_Model_Videos $newVideos a fresh Videos object which has not yet been added to the repository
     * @return void
     * @dontvalidate $newVideos
     */
    public function newAction(Tx_Pfcontest_Domain_Model_Videos $newVideos = null) {
        $this->view->assign('newVideos', $newVideos);
    }

    /**
     * Creates a new Videos and forwards to the list action.
     *
     * @param Tx_Pfcontest_Domain_Model_Videos $newVideos a fresh Videos object which has not yet been added to the repository
     * @return void
     */
    public function createAction(Tx_Pfcontest_Domain_Model_Videos $newVideos) {
        $this->videosRepository->add($newVideos);
        $this->flashMessageContainer->add('Your new Videos was created.');
        $this->redirect('list');
    }

    /**
     * Displays a form for editing an existing Videos
     *
     * @param Tx_Pfcontest_Domain_Model_Videos $videos the Videos to display
     * @return string A form to edit a Videos
     */
    public function editAction(Tx_Pfcontest_Domain_Model_Videos $videos) {
        $this->view->assign('img_videos', $videos);
    }

    /**
     * Updates an existing Videos and forwards to the list action afterwards.
     *
     * @param Tx_Pfcontest_Domain_Model_Videos $videos the Videos to display
     * @return
     */
    public function updateAction(Tx_Pfcontest_Domain_Model_Videos $videos) {
        $this->videosRepository->update($videos);
        $this->flashMessageContainer->add('Your Videos was updated.');
        $this->redirect('list');
    }

    /**
     * Deletes an existing Videos
     *
     * @param Tx_Pfcontest_Domain_Model_Videos $videos the Videos to be deleted
     * @return void
     */
    public function deleteAction(Tx_Pfcontest_Domain_Model_Videos $videos) {
        $this->videosRepository->remove($videos);
        $this->flashMessageContainer->add('Your Videos was removed.');
        $this->redirect('list');
    }



}

// Vergleichsfunktion
function vergleich($wert_a, $wert_b) {
    // Sortierung nach dem zweiten Wert des Array (Index: 1)
    $a = preg_replace('(\-|T|Z|\:|\.)', '' , $wert_a['videoRecorded']);
    $b = preg_replace('(\-|T|Z|\:|\.)', '' , $wert_b['videoRecorded']);

    if ($a == $b) {
        return 0;
    }

    return ($a > $b) ? -1 : +1;
}
?>